import BlockButton from '@/components/BlockButton';
import Dialog from '@/components/Dialog';
import { AppContext } from '@/store/index.context';
import { forEach } from 'lodash';
import React, {
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useState,
} from 'react';
import { useNavigate } from 'react-router-dom';
import classes from './index.module.css';
import ShowPoints from '../components/ShowPoints';

export default function GameResult({
  setShowGameResult,
  icons,
}: {
  setShowGameResult: (bol: boolean) => void;
  icons: string[];
}) {
  const { gameStore, personStore, historyGamesStore } = useContext(AppContext);
  const { getGameCloseResult, getPositionPersonIds, clearGame } = gameStore;
  const [scores, setScores] = useState<number[]>([]);
  const { getPersonsByIds } = personStore;
  const { unshiftGame } = historyGamesStore;
  const navigate = useNavigate();

  const handleBack = useCallback(() => {
    setShowGameResult(false);
  }, [setShowGameResult]);

  // 结算比赛
  const handleConfirm = useCallback(() => {
    // 点击确定
    unshiftGame(clearGame());
    navigate(-1);
  }, [unshiftGame, clearGame, navigate]);

  useEffect(() => {
    const scores = getGameCloseResult();
    setScores(scores);
  }, [getGameCloseResult]);

  const infos: { name?: string; score: number }[] = useMemo(() => {
    if (scores.length) {
      const persons = getPersonsByIds(getPositionPersonIds());
      const tempInfos: { name?: string; score: number }[] = [];
      forEach(persons, (p, i) => {
        tempInfos[i] = {
          name: p?.name,
          score: scores[i + 1],
        };
      });
      tempInfos.sort((a, b) => b.score - a.score);
      return tempInfos;
    }
    return [];
  }, [scores, getPersonsByIds, getPositionPersonIds]);

  return (
    <Dialog title="得分结算">
      <>
        <div className={classes.ScoreList}>
          {infos.map((info, index) => (
            <ShowPoints
              info={{
                name: info.name || '',
                icon: icons[index],
                score: info.score,
              }}
              key={index}
            />
          ))}
        </div>
        <div className={classes.Footer}>
          <BlockButton text="返回" onClick={handleBack}></BlockButton>
          <BlockButton
            type="primary"
            text="确定"
            onClick={handleConfirm}></BlockButton>
        </div>
      </>
    </Dialog>
  );
}
